import random, jinja2, os, webapp2, urllib, cgi
import webapp2_extras.security as websecurity
import sessions, displugged, logger
from google.appengine.ext import db
from google.appengine.api import mail, users
from datatypes import *

MAX_COOKIE_AGE = 3600*24*365 #Let's make it a year

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class SignupPost(webapp2.RequestHandler):
    def post(self):
        current_user = users.get_current_user()
        if not users.get_current_user():
            self.redirect('/')
            return
        fName = self.request.get("fName")
        mName = self.request.get("mName")
        lName = self.request.get("lName")
        user_id = current_user.user_id()
        email = current_user.email()
        username = self.request.get("username")
        nickname = current_user.nickname()

        #look for other users with the same username
        otherUsersNonUnique = User.all().ancestor(UserPathGen()
                                            ).filter("username =", username)

        if otherUsersNonUnique.count() > 0:
            self.response.out.write("Username already chosen.")
            return
        
        newUser = User(parent = UserPathGen(), key_name = username)
        newUser.user_id = user_id
        newUser.email = email
        newUser.username = username
        newUser.firstName = fName
        newUser.middleName = mName
        newUser.lastName = lName
        newUser.nickname = nickname
        newUser.bio = db.Text()
        
        newUser.put()

        self.response.out.write(
            "Account successfully created!")
        self.redirect('/')
        #more stuff to tell the user they're in!
        logger.log("New user {0} created.".format(newUser.username))

class checkUsername(webapp2.RequestHandler):
    def post(self):
        checking = self.request.get("username")
        otherUsersNonUnique = User.all().ancestor(UserPathGen()
                                            ).filter("username =", checking)
        if sessions.isRegistered():
            otherUsersNonUnique.filter('key =', sessions.ourUserModel().key())
                                    
        if otherUsersNonUnique.count() > 0:
            self.response.out.write(":(")
        else:
            self.response.out.write(":)")
        
class listusers(webapp2.RequestHandler):
    def get(self):
        if sessions.adminOrGtfo(self): return
        people = db.GqlQuery("SELECT * "
                                "FROM User "
                                "ORDER BY isAdmin,lastName")
        # print list of users
        self.response.out.write("<table border='1'><tr><td>fname</td><td>lname</td><td>email</td><td>isAdmin</td><td>username</td></tr>")
        for person in people:
            self.response.out.write("<tr>")
            self.response.out.write("<td> %s </td>" % cgi.escape(person.firstName))
            self.response.out.write("<td> %s </td>" % cgi.escape(person.lastName))
            self.response.out.write("<td> %s </td>" % cgi.escape(person.email))
            self.response.out.write("<td> %s </td>" % str(person.isAdmin))
            self.response.out.write("<td> %s </td>" % cgi.escape(person.username))
            self.response.out.write("<td><a href='delete?user=%s'>Delete</a></td>" % urllib.quote(person.username))
            self.response.out.write("<td><a href='makeAdmin?user=%s'>Make Admin</a></td>" % urllib.quote(person.username))
        self.response.out.write("</table>")
        logger.log("Administrator {0} viewed a list of all users.".format(
            sessions.nameFromUserModel()))

class deleteUser(webapp2.RequestHandler):
    def get(self):
        #load variables
        user = urllib.unquote(self.request.get('user'))
        sure = self.request.get('sure')
        if not (sessions.ourUserModel().username == user or sessions.isAdmin()):
            displugged.giveError(self, "You do not have permission to perform this action.")
            return 
        if sure!='1':
            self.response.out.write("ARE YOU SURE YOU WANT TO DELETE <b>"+user+"</b>?<br />")
            self.response.out.write("<a href = 'delete?user=%s&sure=1'> YES </a>" % urllib.quote(user))
        else:
            user = User.get_by_key_name(user, parent=UserPathGen())
            if user:
                logger.log("User account {0} deleted.".format(
                    sessions.nameFromUserModel()))
                user.delete()
                self.response.out.write("Account deleted. Sad to see you go.:(")
                
            else:
                logger.log("User deletion attempt was made but no such user {0} existed".format(user))
                displugged.giveError(self,
                    "The user {0} was not found. This incident will be reported.".format(
                    cgi.escape(str(user))))

class makeAdmin(webapp2.RequestHandler):
    def get(self):
        user = urllib.unquote(self.request.get('user'))
        if sessions.adminOrGtfo(self): return
        user = User.get_by_key_name(user)
        if not user:
            logger.log("{0} attempted to make admin, doesn't exist.".format(
                sessions.nameFromUserModel()))
            return
        else:
            if user.isAdmin:
                self.response.out.write("User was already admin.")
                logger.log("Attempt made to re-admin {0} by {1}".format(
                    user.username, sessions.nameFromUserModel()))
            else:
                user.isAdmin = True
                logger.log("{0} made admin by {1}".format(
                    user.username, sessions.nameFromUserModel()))
                user.put()

app = webapp2.WSGIApplication([('/account/signup', SignupPost),
                               ('/account/check_username',checkUsername),
                               ('/account/listusers',listusers),
                               ('/account/delete',deleteUser),
                               ('/account/makeAdmin',makeAdmin)],
                              debug=True,
                              config={'webapp2_extras.sessions':
                                      {'secret_key':'secret password to come'}})
